<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item
        label="产品名称"
        prop="productName"
      >
        <el-input
          v-model="queryParams.productName"
          placeholder="请输入产品名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
        >搜索</el-button>
        <el-button
          icon="el-icon-refresh"
          size="mini"
          @click="resetQuery"
        >重置</el-button>
      </el-form-item>
    </el-form>

    <el-row
      :gutter="10"
      class="mb8"
    >
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:type:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
          v-hasPermi="['system:type:import']"
        >导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:type:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-sort"
          size="mini"
          @click="toggleExpandAll"
        >展开/折叠</el-button>
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-if="refreshTable"
      v-loading="loading"
      :data="typeList"
      row-key="id"
      :default-expand-all="isExpandAll"
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
    >
      <el-table-column
        prop="productName"
        label="产品名称"
      ></el-table-column>
      <el-table-column
        prop="productCode"
        label="产品编码"
      ></el-table-column>
      <el-table-column
        prop="sort"
        label="排序"
        width="60"
      ></el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:type:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-plus"
            @click="handleAdd(scope.row)"
            v-hasPermi="['system:type:add']"
          >新增</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:menu:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改产品类型对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="500px"
      append-to-body
    >
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item
          label="产品名称"
          prop="productName"
        >
          <el-input
            v-model="form.productName"
            placeholder="请输入产品名称"
          />
        </el-form-item>
        <el-form-item
          label="产品编码"
          prop="productCode"
        >
          <el-input
            v-model="form.productCode"
            placeholder="请输入产品编码"
          />
        </el-form-item>
        <el-form-item
          label="上级分类"
          prop="parentProductId"
        >
          <treeselect
            v-model="form.parentProductId=='0'?null:form.parentProductId"
            :options="productTypeOptions"
            :normalizer="normalizer"
            :show-count="true"
            placeholder="选择上级分类"
          />
        </el-form-item>
        <el-form-item label="图标" prop="imagePath">
          <image-upload
            :fileType="fileType"
            :limit="limit"
            v-model="form.imagePath"
          ></image-upload>
        </el-form-item>
        <el-form-item
          label="排序"
          prop="sort"
        >
          <el-input-number
            v-model="form.sort"
            placeholder="请输入排序"
            :min="0"
          />
        </el-form-item>
        <el-form-item label="关联文档">
          <file-up
            @input="handleUploadSuccess"
            :file-list="fileList"
            ref="fileUp"
          >
          </file-up>

        </el-form-item>
        <el-table v-loading="fileLoading" :data="fileList">
          <el-table-column label="名称" align="center" prop="fileName"/>
          <el-table-column label="上传时间" align="center" prop="createTime"/>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-download"
                @click="handleUpload(scope.row)"
                v-hasPermi="['system:file:upload']"
              >下载</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDeleteFile(scope.row)"
                v-hasPermi="['system:file:remove']"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div
        slot="footer"
        class="dialog-footer"
      >
        <el-button
          type="primary"
          @click="submitForm"
        >确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 产品类型导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listType, getType, delType, addType, updateType } from "@/api/system/type";
import { listFilesByIds,delFiles } from "@/api/system/files";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import axios from "axios";
import { blobValidate } from "@/utils/ruoyi";
import { getToken } from '@/utils/auth'
import errorCode from '@/utils/errorCode'
import {Message} from "element-ui";
const baseURL = process.env.VUE_APP_BASE_API
export default {
  name: "Type",
  components: { Treeselect },
  data () {
    return {
      // 遮罩层
      loading: true,
      //文件遮罩层
      fileLoading:true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 产品类型表格数据
      typeList: [],
      // 弹出层标题
      title: "",
      // 重新渲染表格状态
      refreshTable: true,
      // 是否显示弹出层
      open: false,
      // 是否展开，默认全部折叠
      isExpandAll: false,
      // 菜单树选项
      productTypeOptions: [],
      //上传图片类型
      fileType:["png"],
      //文件列表
      fileList:[],
      fileIds:[],
      updateOperation:false,
      limit:1,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        productName: null,
        parentProductId: null,
        productCode: null,
        imagePath: null,
        attachmentId: null,
        sort: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        productName: [
          { required: true, message: "产品名称不能为空", trigger: "blur" }
        ],
      },
      // 产品类型导入参数
      upload: {
        // 是否显示弹出层
        open: false,
        // 弹出层标题
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的客户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/system/type/importData"
      },
    };
  },
  created () {
    this.getList();
  },
  methods: {
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "产品类型导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download('system/type/importTemplate', {
      }, `productType_template_${new Date().getTime()}.xlsx`)
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    /** 查询产品类型列表 */
    getList () {
      this.loading = true;
      listType(this.queryParams).then(response => {
        this.typeList = this.handleTree(response.data, "id", "parentProductId");
        this.loading = false;
      });
    },
    /** 转换菜单数据结构 */
    normalizer (node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.productName,
        children: node.children
      };
    },
    /** 展开/折叠操作 */
    toggleExpandAll () {
      this.refreshTable = false;
      this.isExpandAll = !this.isExpandAll;
      this.$nextTick(() => {
        this.refreshTable = true;
      });
    },
    /** 查询文件列表 */
    getFileList() {
      this.fileLoading = true;
      if(this.fileIds.length > 0){
        listFilesByIds(this.fileIds).then(response => {
          this.fileList = response
          this.$refs.fileUp.fileList=response;
          this.fileLoading = false;
        });
      }else{
        this.fileList = [];
        this.fileLoading = false;
      }
    },
    // 上传成功回调
    handleUploadSuccess(res, file) {
      this.fileIds.push(res.fileId);
      this.getFileList();
    },
    // 取消按钮
    cancel () {
      this.open = false;
      this.reset();
      this.$refs.fileUp.fileList=[];
    },
    // 表单重置
    reset () {
      this.form = {
        id: null,
        productName: null,
        parentProductId: null,
        productCode: null,
        imagePath: null,
        attachmentId: null,
        sort: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.fileIds = [];
      this.fileList = [];

      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery () {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery () {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange (selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd (row) {
      this.reset();
      if (row != undefined) {
        this.form.parentProductId = row.id;
      }
      this.open = true;
      this.title = "添加产品类型";
      listType().then(response => {
        this.productTypeOptions = this.handleTree(response.data, "id", "parentProductId");
      });
      this.getFileList();
    },
    /** 修改按钮操作 */
    handleUpdate (row) {
      this.updateOperation = true;
      this.reset();
      const id = row.id || this.ids
      getType(id).then(response => {
        this.form = response.data;
        if(response.data.attachmentId != undefined && response.data.attachmentId!= '' && response.data.attachmentId!=null){
          this.fileIds = response.data.attachmentId.split(",")
        }
        this.open = true;
        this.title = "修改产品类型";
        this.getFileList();
      })
      listType().then(response => {
        this.productTypeOptions = this.handleTree(response.data, "id", "parentProductId");
      });;
    },
    /** 提交按钮 */
    submitForm () {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            this.form.attachmentId = this.fileIds.toString()
            updateType(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            this.form.attachmentId = this.fileIds.toString()
            addType(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete (row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除产品类型编号为"' + ids + '"的数据项？').then(function () {
        return delType(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 删除文件按钮操作 */
    handleDeleteFile (row) {
      const ids = row.fileId || this.ids;
      this.$modal.confirm('是否确认删除此文件？').then( () => {
        if(this.updateOperation){
          for (var i = 0; i < this.fileIds.length; i++) {
            if(this.fileIds[i] === ids+""){
              this.fileIds.splice(i,1)
            }
          }
        }else{
          for (var i = 0; i < this.fileIds.length; i++) {
            if(this.fileIds[i] === ids){
              this.fileIds.splice(i,1)
            }
          }
        }
        return delFiles(ids);
      }).then(() => {
        this.getFileList()
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    handleUpload(row){
      var url = baseURL + "/common/download/resource?resource=" + encodeURI(row.filePath);
      // location.href=url;
      axios({
        method: 'get',
        url: url,
        responseType: 'blob',
      }).then(async (res) => {
        const isLogin = await blobValidate(res.data);
        if (isLogin) {
          const blob = new Blob([res.data])
          this.saveAs(blob, decodeURI(res.headers['download-filename']))
        } else {
          this.printErrMsg(res.data);
        }
      })
    },
    /** 导出按钮操作 */
    handleExport () {
      this.download('system/type/export', {
        ...this.queryParams
      }, `type_${new Date().getTime()}.xlsx`)
    },
    saveAs(text, name, opts) {
      saveAs(text, name, opts);
    },
    async printErrMsg(data) {
      const resText = await data.text();
      const rspObj = JSON.parse(resText);
      const errMsg = errorCode[rspObj.code] || rspObj.msg || errorCode['default']
      Message.error(errMsg);
    }
  }
};
</script>
